package com.chromatic.competition.service;

import android.os.AsyncTask;
import android.util.Log;

import androidx.annotation.NonNull;

import com.chromatic.competition.inteface.ChatHistoryCallback;
import com.chromatic.competition.inteface.UserInitializationService;
import com.chromatic.competition.model.UserMessage;
import com.chromatic.competition.utils.RetrofitClientUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MessagesDatabaseService {
    private static ChatHistoryCallback chatHistoryCallback;

    public void setChatHistoryCallback(ChatHistoryCallback callback) {
        chatHistoryCallback = callback;
    }

    public void fetchChatHistory(int currentUserId, int friendId) {
        RetrofitClientUtil retrofitClientUtil = RetrofitClientUtil.getInstance();
        UserInitializationService userInitializationService = retrofitClientUtil.getApiService();

        Call<List<UserMessage>> call = userInitializationService.getMessagesBetweenUsers(currentUserId, friendId);
        call.enqueue(new Callback<>() {
            public void onResponse(@NonNull Call<List<UserMessage>> call, @NonNull Response<List<UserMessage>> response) {
                if (response.isSuccessful()) {
                    List<UserMessage> messages = response.body();
                    // 处理获取到的消息列表
                    if (chatHistoryCallback != null) chatHistoryCallback.onChatHistoryLoaded(messages);
                } else {
                    // 处理请求失败的情况
                    Log.e("MessagesDatabaseService的fetchChatHistory方法", "响应有问题，获取聊天历史记录出错. Response code: " + response.code());
                }
            }
            public void onFailure(@NonNull Call<List<UserMessage>> call, @NonNull Throwable t) {
                // 处理请求失败的情况
                Log.e("MessagesDatabaseService的fetchChatHistory方法", "网络有问题，获取聊天历史记录出错. Error: " + t.getMessage());
            }
        });
    }

    public void sendMessage(UserMessage userMessage) {
        new SendMessageTask().execute(userMessage);
    }

    /**
     * 异步任务，用于保存消息
     */
    private static class SendMessageTask extends AsyncTask<UserMessage, Void, Void> {
        @Override
        protected Void doInBackground(UserMessage... userMessages) {
            UserMessage userMessage = userMessages[0];

            try {
                // 建立数据库连接
                Connection connection = DriverManager.getConnection("jdbc:mysql://47.113.190.59:3306/sk_iot_app?useSSL=false",
                        "remote", "mysqlRemote");

                // 构建 SQL 插入语句
                String sql = "INSERT INTO user_messages (sender_id, receiver_id, content, timestamp) VALUES (?, ?, ?, ?)";

                // 创建预编译语句对象
                PreparedStatement statement = connection.prepareStatement(sql);

                // 设置参数值
                statement.setInt(1, userMessage.getSenderId());
                statement.setInt(2, userMessage.getReceiverId());
                statement.setString(3, userMessage.getText());
                statement.setString(4, userMessage.getTimestamp());

                // 执行插入操作
                statement.executeUpdate();
                Log.d("聊天界面提示：","新消息已成功写入数据库！");

                // 关闭语句对象和数据库连接
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}